import { login, getMenu } from '@/api/login'
import { setToken, getToken } from '@/utils/auth'


const user = {
	state: {
		token: getToken(),
		menu: {},
		buttonMap: {}
	},
	mutations: {
		SET_TOKEN: (state, token) => {
			state.token = token
		},
		SET_MENU: (state, menu) => {
			state.menu = menu
		},
		SET_BUTTON_MAP: (state, buttonMap) => {
			state.buttonMap = buttonMap
		}		
	},
	actions: {
		Login: ({ commit }, userInfo) => {
			const username = userInfo.userName.trim()
			const password = userInfo.password.trim()
			return new Promise((resolve, reject) => {
				var params = new URLSearchParams()
				params.append('username', username)
				params.append('password', password)
				login(params).then(response => {
				const data = response.data.data
				setToken(data.token)
				commit('SET_TOKEN', data.token)
				resolve(response)
				}).catch(error => {
				reject(error)
				})
			})
		},
		// 获取菜单列表
		GetMenu({ commit }) {
			return new Promise((resolve, reject) => {
			getMenu().then(response => {
				const data = response.data.data
				console.log("获取的菜单", data)
				// 这里对按钮进行一些处理
				let buttonList = data.buttonList
				let map = new Map();
				for(let a=0; a<buttonList.length; a++) {
					map.set(buttonList[a].url, buttonList[a])
				}
				commit('SET_BUTTON_MAP', map)
				commit('SET_MENU', data)
				resolve(response)
			}).catch(error => {
				reject(error)
			})
			})
		}		
	}
}

export default user